import React, { useEffect, useState, useMemo } from 'react'
import moment from 'moment';
import { RouteRequest } from '@peace/utils';
import { WEATHERArr, WEATHERMARGIN, ICONSMAP } from '../constants/weather'

function Weather() {
    const [time, setTime] = useState(new Date().toLocaleTimeString());
    const [weather, setWeather] = useState('');
    const [temp, setTemp] = useState([0, 0]);

    useEffect(() => {
        const timeUpdate = setInterval(() => {
            setTime(new Date().toLocaleTimeString());
        }, 1000);
        return () => {
            clearInterval(timeUpdate);
        };
    }, []);

    const queryWeather = () => {
        RouteRequest.get(`/query/weather/3d?location=101240101`).then((res) => {
            if (res?.daily?.length === 3) {
                setWeather(res.daily[0].textDay || '未知')
                setTemp([res.daily[0].tempMin, res.daily[0].tempMax]);
            }
        });
    };

    useEffect(() => {
        queryWeather();
        const timeUpdate = setInterval(() => {
            queryWeather();
        }, WEATHERMARGIN);
        return () => {
            clearInterval(timeUpdate);
        };
    }, []);

    const iconSrc = useMemo(() => {
        const icon = ICONSMAP[weather];
        if (icon) return icon;
        const rgx = new RegExp(weather);
        for (const k in ICONSMAP) {
            if (rgx.test(k)) {
                return ICONSMAP[k];
            }
        }
        return '';
    }, [weather]);

    return <div className='_weather_container'>
        <div className='column1'>
            <div>{moment().format('YYYY-MM-DD')}</div>
            <div style={{ fontSize: 14 }}>{time}</div>
        </div>
        <div className='_divider'></div>
        <img src={iconSrc} alt="icon" style={{ width: 43, height: 38, margin: '0 5px' }} />
        <div className='column2'>
            <div>{weather}</div>
            <div style={{ fontSize: 14 }}>{temp[0]}℃-{temp[1]}℃</div>
        </div>
    </div>
}

export default Weather;


